package com.halixun.d2app.dialog;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.halixun.d2app.R;
import com.halixun.d2app.utils.ToastUtils;
import com.halixun.d2app.view.NumberKeyBoxView;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * A simple {@link Fragment} subclass.
 */
public class NumDialogFragment extends DialogFragment implements View.OnClickListener {

    private EditText number;

    private NumDialogListener listener;

    private ViewGroup keyboard;

    public NumDialogFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_num_dialog, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        setListeners(view);
    }

    @Override
    public void onResume() {
        super.onResume();
        number.postDelayed(()->number.setInputType(InputType.TYPE_CLASS_NUMBER),50);
    }

    private void setListeners(View view) {
        for (int i = 0 ; i < keyboard.getChildCount();i++){
            View childView = keyboard.getChildAt(i);
            if (childView instanceof ViewGroup){
                ViewGroup lineView = (ViewGroup) childView;
                for (int j = 0 ; j < lineView.getChildCount() ; j ++){
                    View twoView = lineView.getChildAt(j);
                    if (twoView instanceof TextView){
                        twoView.setOnClickListener(this);
                    }
                }
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView(View view) {
        number = view.findViewById(R.id.number);
        number.setInputType(InputType.TYPE_NULL);

        keyboard = view.findViewById(R.id.keyboard);

        number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String value = s.toString().trim();
                if (TextUtils.isEmpty(value))return;
                if (value.length()>4){
                    String newValue = value.substring(0,value.length()-1);
                    number.setText(newValue);
                    number.setSelection(newValue.length());
                }
            }
        });



//        number.setOnTouchListener((v,event)->{
//            if (event.getAction() == MotionEvent.ACTION_UP) {
//                hintBort((EditText) v);
//                mNumberKeyBoxView.setVisibility(mNumberKeyBoxView.getVisibility()==View.VISIBLE?View.GONE:View.VISIBLE);
//            }
//            return false;
//        });
    }

    private boolean hintBort(EditText v) {
        boolean flag = false;
        EditText edit = v;
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();// isOpen若返回true，则表示输入法打开
        if (isOpen) {
            if (imm.hideSoftInputFromWindow(edit.getWindowToken(), 0))
                flag = true;
        }
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }

        if (methodName == null) {
            edit.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName,
                        boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(edit, false);
            } catch (NoSuchMethodException e) {
                edit.setInputType(InputType.TYPE_NULL);
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    @Override
    public void onClick(View v) {
        if (v instanceof TextView){
            TextView tv = (TextView) v;
            String name = tv.getText().toString();
            if (TextUtils.isEmpty(name))return;
            switch (name){
                case "0":
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                    number.append(name);
                    break;
                case "确认":
                    String num = number.getText().toString().trim();
                    if (TextUtils.isEmpty(num)) {
                        num = "1";
                    }
                    if (null != listener) {
                        listener.onNumDialogClickListener(num);
                    }
                    number.setText("");
                    dismiss();
                    break;
                case "删除":
                    String value = number.getText().toString();
                    if (!TextUtils.isEmpty(value)){
                        String newValue = value.substring(0, value.length() - 1);
                        number.setText(newValue);
                        number.setSelection(newValue.length());
                    }
                    break;
            }
        }



        switch (v.getId()) {


//            case R.id.confirm:
//                String num = number.getText().toString().trim();
//                if (TextUtils.isEmpty(num)) {
//                    ToastUtils.showBottomToast("请输入数目");
//                    return;
//                }
//                if (Integer.valueOf(num) == 0) {
//                    ToastUtils.showBottomToast("输入数目不能为0");
//                    return;
//                }
//                if (null != listener) {
//                    listener.onNumDialogClickListener(num);
//                }
//            case R.id.cancel:
//                number.setText("");
//                dismiss();
//                break;
        }
    }

    public void setNumDialogListener(NumDialogListener listener) {
        this.listener = listener;
    }

    public interface NumDialogListener {
        void onNumDialogClickListener(String number);
    }

}
